package Junit;

import java.io.File;

import domain.users.User;
import persistence.XMLFileHandler;
import persistence.XMLUserRepository;
import junit.framework.TestCase;

public class XMLUserRepositoryTest extends TestCase {

	private XMLUserRepository xmluser;
	Object object;
	XMLFileHandler handler;
	String username1 = "bimbalolo";
	String password1 = "mummy";
	String username2 = "jonny";
	String password2 = "1234";

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		this.object = null;
		this.handler = new XMLFileHandler();
		this.handler.saveDB(object, new File("testuser.xml"));
		this.xmluser = new XMLUserRepository("testuser.xml");

	}

	public void testAddUser() throws Exception {
		try {
			setUp();
		} catch (Exception e) {
			fail();
		}
		assertNotNull(this.xmluser);
		assertFalse(this.xmluser.authenticate(username1, password1));
		assertTrue(this.xmluser.addUser(username1,"abc@gmail.com",password1));
		assertTrue(this.xmluser.authenticate(username1, password1));
		assertFalse(this.xmluser.addUser(username1,"abc@gmail.com",password1));
		assertFalse(this.xmluser.authenticate(username2, password2));
	}

	public void testAuthenticate() {
		try {
			setUp();
		} catch (Exception e) {
			fail();
		}
		assertFalse(this.xmluser.authenticate(username1, password1));
		assertTrue(this.xmluser.addUser(username1,"abc@gmail.com", password1));
		assertFalse(this.xmluser.authenticate(username1, password2));
		assertFalse(this.xmluser.authenticate(username2, password1));
		assertTrue(this.xmluser.authenticate(username1, password1));
		assertFalse(this.xmluser.addUser(username1,"abc@gmail.com", password1));
		assertFalse(this.xmluser.authenticate(username2, password2));
	}

	public void testGetUser() {
		try {
			setUp();
		} catch (Exception e) {
			fail();
		}
		User o1 = this.xmluser.getUser(username1);
		assertNull(o1);
		User o2 = this.xmluser.getUser(username2);
		assertNull(o2);
		assertTrue(this.xmluser.addUser(username1,"abc@gmail.com", password1));
		o1 = this.xmluser.getUser(username1);
		assertNotNull(o1);
		o2 = this.xmluser.getUser(username2);
		assertNull(o2);
		assertTrue(this.xmluser.addUser(username2,"abc@gmail.com", password2));
		o1 = this.xmluser.getUser(username1);
		assertNotNull(o1);
		o2 = this.xmluser.getUser(username2);
		assertNotNull(o2);
	}

	public void testExists() {
		try {
			setUp();
		} catch (Exception e) {
			fail();
		}
		assertFalse(this.xmluser.exists(username1));
		assertFalse(this.xmluser.exists(username2));
		assertTrue(this.xmluser.addUser(username1,"abc@gmail.com", password1));
		assertTrue(this.xmluser.exists(username1));
		assertFalse(this.xmluser.exists(username2));
		assertTrue(this.xmluser.addUser(username2,"abc@gmail.com", password2));
		assertTrue(this.xmluser.exists(username1));
		assertTrue(this.xmluser.exists(username2));
	}

}
